package com.downloading.bezoyaapp.getData;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.downloading.bezoyaapp.support.utils.Constraints;

class DB extends SQLiteOpenHelper {

	final static int DB_VERSION = 1;
	Context context;

	public DB(Context context) {
		super(context, Constraints.DB_NAME, null, DB_VERSION);
		// Store the context for later use
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase database) {
		executeSQLScript(database, Constraints.DB_NAME);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	private void executeSQLScript(SQLiteDatabase database, String dbName) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		byte buf[] = new byte[1024];
		int len;
		AssetManager assetManager = context.getAssets();
		InputStream inputStream = null;

		try {
			inputStream = assetManager.open(dbName);
			while ((len = inputStream.read(buf)) != -1) {
				outputStream.write(buf, 0, len);
			}
			outputStream.close();
			inputStream.close();
			String[] createScript = outputStream.toString().split(";");
			for (int i = 0; i < createScript.length; i++) {
				String sqlStatement = createScript[i].trim();
				// TODO You may want to parse out comments here
				if (sqlStatement.length() > 0) {
					database.execSQL(sqlStatement + ";");
				}
			}
		} catch (IOException e) {
			// TODO Handle Script Failed to Load
		} catch (SQLException e) {
			// TODO Handle Script Failed to Execute
		}
	}
}